<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import {
  NSpace,
  NButton,
  NForm,
  NInput,
  NFormItem,
  NCard,
  useMessage,
  type FormInst,
  type FormRules
} from 'naive-ui'
import { useRoute, useRouter } from 'vue-router'
import Cookies from 'js-cookie'
import { aes } from '@/utils/crypto'
import { setToken } from '@/utils/auth'
import { sendRequest } from '@/utils/api'

const message = useMessage()
const router = useRouter()
const route = useRoute()

//   表单数据
const form: any = ref({
  username: '',
  password: '',
  captcha: '',
  checkKey: ''
})
const captcha = ref<string | undefined>(undefined)
// 表单组件实例
const formRef = ref<FormInst | null>(null)

// 表单验证
const rules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ],
  captcha: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    }
  ]
}

const username = computed(() => aes.en(form.value.username))
const password = computed(() => aes.en(form.value.password))

// 获取验证码
async function queryCaptcha() {
  const [error, data] = await sendRequest({
    module: 'sys',
    api: 'captcha'
  })

  if (error) throw new Error(error.message)
  form.value.checkKey = data.data.key
  captcha.value = data.data.image
}

// 提交表单
function submitForm(e: any) {
  e.preventDefault()
  formRef.value?.validate(async (error) => {
    if (error) return

    try {
      const [error, data] = await sendRequest({
        module: 'sys',
        api: 'login',
        override: {
          data: {
            username: username.value,
            password: password.value,
            captcha: form.value.captcha
            // checkKey: form.value.checkKey
          }
        }
      })

      if (error) throw new Error(error.message)
      if (data.code !== 0) throw new Error(data.msg)
      Cookies.set('username', form.value.username)
      Cookies.set('password', form.value.password)
      message.success('登录成功')
      setToken(data.data.token)
      router.push({ path: (route.query.redirect as string) || '/' })
    } catch (error: any) {
      message.error(error.message)
      queryCaptcha()
    }
  })
}

function handleKeydown(e: KeyboardEvent) {
  if (e.key !== 'Enter') return
  submitForm(e)
}

const inputTheme = { heightMedium: '40px' }

onMounted(() => {
  queryCaptcha()
  form.value.username = Cookies.get('username')
  form.value.password = Cookies.get('password')
})
</script>

<template>
  <div justify="center" class="main">
    <NCard style="width: 271px;height: 256px; border: none;background:rgba(0,0,0,.66);margin-top: 144px">
      <div class="title">账号密码登录</div>
      <div class="line"></div>
      <NForm ref="formRef" :model="form" :rules="rules" label-placement="left" :label-width="0"
        :onKeydown="handleKeydown">
        <NFormItem path="username">
          <NInput v-model:value="form.username" placeholder="请输入账号" :theme-overrides="inputTheme">
            <template #prefix>
              <img src="@/assets/images/user.png" />
            </template>
          </NInput>
        </NFormItem>

        <NFormItem path="password">
          <NInput type="password" v-model:value="form.password" placeholder="请输入密码" :theme-overrides="inputTheme">

            <template #prefix>
              <img src="@/assets/images/lock.png" />
            </template>
          </NInput>
        </NFormItem>

        <!-- <NFormItem path="captcha">
          <NInput
            v-model:value="form.captcha"
            placeholder="验证码"
          />
          <img
            :src="captcha"
            alt="验证码"
          />
        </NFormItem> -->
        <NFormItem>
          <NButton type="success" @click="submitForm" style="width: 100%;">
            登 录
          </NButton>
        </NFormItem>
      </NForm>
    </NCard>
  </div>
</template>

<style scoped lang="scss">
.main {
  display: flex;
  justify-content: center;
  height: 100%;
  background: url('@/assets/images/bglogo-other.jpg') no-repeat;
  background-size: 100% 100%;
}

.title {
  margin-left: 50px;
  margin-bottom: 10px;
  width: 106px;
  height: 22px;
  line-height: 22px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 16px;
  color: #FFFFFF;
  letter-spacing: 1px;
  font-style: normal;
}

.line {
  margin-left: 50px;
  margin-bottom: 30px;
  width: 103px;
  height: 2px;
  background: #5FB17F;
}

:deep(.n-input__prefix) {
  margin-left: -12px;
  width: 40px;
  height: 40px;
  background-color: #AAABAB;
}

:deep(.n-input .n-input-wrappe) {
  height: 40px;
  line-height: 40px;
}

:deep(.n-input__input-el) {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 16px;
  letter-spacing: 1px;
  font-style: normal;
  font-size: 16px;
}
</style>
